package locks.dead.active;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * 活锁  :  两个人相互转账时候出现
 *
 * 例如： a.transfer(b,10)   b.transfer(a,10);
 *
 */
public class Account {
    private int balance;
    private final Lock lock
            = new ReentrantLock();

    // 转账
    void transfer(Account tar, int amt) throws Exception {
        while (true) {
            if (this.lock.tryLock()) {
                try {
                    if (tar.lock.tryLock()) {
                        try {
                            this.balance -= amt;
                            tar.balance += amt;
                            //新增：退出循环
                            break;
                        } finally {
                            tar.lock.unlock();
                        }
                    }//if
                } finally {
                    this.lock.unlock();
                }
            }

            //此处还可以加一个 超时时间判断在指定时间 否则失败


            //新增：sleep一个随机时间避免活锁
            Thread.sleep(11);
        }//while
    }//transfer
}